package com.shareppy.normanhttp.tasks;

import android.os.AsyncTask;

public class TaskExecutor {

	public static boolean running;

	public static <PARAMS extends BgTaskParams, RESULT> void execute(//
			final SppyBgTask<PARAMS, RESULT> task, //
			final PARAMS params,//
			final TaskCallback<RESULT> callback//
	) {
		@SuppressWarnings("unchecked")
		final AsyncTask<PARAMS, Void, RESULT> executor = task.execute(params);
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (running) {
					System.out.println("La tarea no se puede ejecutar por que la anterior no se ha terminado.");
				}else{
					running = true;
					try {
						final RESULT value = executor.get();
						running = false;
						if (value instanceof TaskException) {
							throw (TaskException) value;
						} else {
							callback.onResponse(value);
						}
					} catch (final Throwable e) {
						running = false;
						if (e instanceof TaskException) {
							callback.onError((TaskException) e);
						} else {
							callback.onError(new TaskException(e));
						}
					}
				}
			}
		}).start();
	}
}